package com.qianniu.napi.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 证书工具类
 */
public class CertUtil {

    // 微信证书私钥路径（从微信商户平台下载，保存在本地）
    public static String APICLIENT_KEY = "/data/soft/cert_wx/1592907601/apiclient_cert.pem";

    // 微信商户证书路径（从微信商户平台下载，保存在本地）
    public static String APICLIENT_CERT = "/data/soft/cert_wx/1592907601/apiclient_cert.pem";

    /**
     * 获取私钥。
     *
     * @param
     * @return 私钥对象
     */
    public static PrivateKey getPrivateKey() throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(APICLIENT_KEY)), StandardCharsets.UTF_8);
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }

    /**
     * 获取商户证书。
     *
     * @param filename 证书文件路径 (required)
     * @return X509证书
     */
    public static X509Certificate getCertificate(String filename) throws IOException {
        InputStream fis = new FileInputStream(APICLIENT_CERT);
        try (BufferedInputStream bis = new BufferedInputStream(fis)) {
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException e) {
            throw new RuntimeException("证书已过期", e);
        } catch (CertificateNotYetValidException e) {
            throw new RuntimeException("证书尚未生效", e);
        } catch (CertificateException e) {
            throw new RuntimeException("无效的证书文件", e);
        }
    }

    /**
     * 获取商户证书序列号
     *
     * @param certPath 获取商户证书序列号 传递商号证书路径 apiclient_cert
     * @return
     * @throws IOException
     */
    public static String getSerialNo(String certPath) throws IOException {
        X509Certificate certificate = getCertificate(certPath);
        return certificate.getSerialNumber().toString(16).toUpperCase();
    }

    /**
     * 获取微信平台证书序列号
     *
     * @return
     * @throws Exception
     */
    public static String getCertSerialNo() throws Exception {
        try {
            String str = HttpUrlUtil.sendGet();
            System.out.println(str);
            JSONObject json = JSONObject.parseObject(str);
            JSONArray jsonArray = JSONArray.parseArray(json.getString("data"));
            JSONObject jsonObject = jsonArray.getJSONObject(0);

            return jsonObject.getString("serial_no");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取微信平台证书
     *
     * @return
     * @throws Exception
     */
    public static String getCertStr() throws Exception {
        try {
            String str = HttpUrlUtil.sendGet();
            JSONObject json = JSONObject.parseObject(str);
            JSONArray jsonArray = JSONArray.parseArray(json.getString("data"));
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            JSONObject jsonCert = JSONObject.parseObject(jsonObject.getString("encrypt_certificate"));
//			System.out.println(str);
//			System.out.println(jsonCert);

//            String certKeyString = AesUtil1.decryptToString(
//                    jsonCert.getString("associated_data").getBytes(),
//                    jsonCert.getString("nonce").getBytes(),
//                    jsonCert.getString("ciphertext"));

            String certKeyString = "";
            return certKeyString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
